package com.yang.sso.oauth.handler;

import com.yang.sso.oauth.result.Result;
import com.yang.sso.oauth.enums.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常捕获
 * @ExceptionHandler 注解表示该方法捕获的异常类型，就可以在不同的异常中进行不同的处理方式
 * @author: Islands
 * @create: 2024-03-02 17:01
 */

@Slf4j
@RestControllerAdvice
public class Oauth2ExceptionHandler {

    @Autowired
    private HttpServletRequest request;

    /**
     * 无效的授予异常
     * @param e
     * @return
     * @param <T>
     */
    @ExceptionHandler(InvalidGrantException.class)
    public <T> Result<T> exceptionHandler(InvalidGrantException e) {
        e.printStackTrace();
        log.error("异常类型:{};请求地址:{};方式:{};参数:{};异常信息:{}","InvalidGrantException",
                request.getRequestURI(),request.getMethod(),
                request.getQueryString(),e.getMessage());

        return Result.failed(ResultCode.AUTHORIZED_ERROR);
    }



    /**
     * 用户名为空
     * @param e
     * @return
     * @param <T>
     */
    @ExceptionHandler(UsernameNotFoundException.class)
    public <T> Result<T> exceptionHandler(UsernameNotFoundException e) {
        e.printStackTrace();
        log.error("异常类型:{};请求地址:{};方式:{};参数:{};异常信息:{}","UsernameNotFoundException",
                request.getRequestURI(),request.getMethod(),
                request.getQueryString(),e.getMessage());
        return Result.failed(ResultCode.AUTHORIZED_ERROR);
    }

}
